package wechat_service

import (
	"context"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/miniprogram"
	"github.com/silenceper/wechat/v2/miniprogram/auth"
	"github.com/silenceper/wechat/v2/miniprogram/business"
	mpConfig "github.com/silenceper/wechat/v2/miniprogram/config"
	"github.com/silenceper/wechat/v2/miniprogram/qrcode"
	"github.com/silenceper/wechat/v2/miniprogram/urlscheme"
	"github.com/spf13/viper"
	"take-a-break/component/config"
)

type MiniProgram struct {
	ctx         context.Context
	wc          *wechat.Wechat
	miniProgram *miniprogram.MiniProgram
}

//NewMiniProgram new
func NewMiniProgram(ctx context.Context) *MiniProgram {
	//init config
	mpCfg := &mpConfig.Config{
		AppID:     config.GetString("wechat.miniprogram.appID"),
		AppSecret: config.GetString("wechat.miniprogram.appSecret"),
	}
	wc := GetWechat()
	miniProgram := wc.GetMiniProgram(mpCfg)
	miniProgram.SetAccessTokenHandle(
		NewCkAccessToken(mpCfg.AppID, mpCfg.AppSecret, "niuren:mini", GetCache()))
	return &MiniProgram{
		ctx:         ctx,
		wc:          wc,
		miniProgram: miniProgram,
	}
}

// Code2Session 通过前端wx.login()传回来的code转换成openid、unionid、session_key等内容
// https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
func (s *MiniProgram) Code2Session(jsCode string) (result auth.ResCode2Session, err error) {
	return s.miniProgram.GetAuth().Code2Session(jsCode)
}

// GetUserPhoneNumber 获取用户手机， 通过前端button(getPhoneNumber)传回来的code进行手机号的获取
// 授权后获取openid时发现当前用户未注册时，提醒用户授权手机号进行注册
// https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
func (s *MiniProgram) GetUserPhoneNumber(code string) (info business.PhoneInfo, err error) {
	in := &business.GetPhoneNumberRequest{
		Code: code,
	}
	return s.miniProgram.GetBusiness().GetPhoneNumber(in)
}

// GenShortLink 生成小程序短链  只能支持电商分类，其他分类无法使用
func (s *MiniProgram) GenShortLink(pageUrl string, pageTitle string) (string, error) {
	return s.miniProgram.GetShortLink().GenerateShortLinkTemp(pageUrl, pageTitle)
}

// GenUrlScheme 生成scheme
func (s *MiniProgram) GenUrlScheme(path, queue string) (string, error) {
	param := &urlscheme.USParams{
		JumpWxa: &urlscheme.JumpWxa{
			Path:       path,
			Query:      queue,
			EnvVersion: urlscheme.EnvVersionDevelop,
		},
		ExpireType:     urlscheme.ExpireTypeInterval,
		ExpireTime:     0,
		ExpireInterval: 7,
	}
	return s.miniProgram.GetSURLScheme().Generate(param)
}

// GetWXACodeUnlimit 获取小程序码
// @Param: page: "pages/index/index"
// @Param: scene: "a=1"
func (s *MiniProgram) GetWXACodeUnlimit(page string, scene string) (response []byte, err error) {
	param := qrcode.QRCoder{
		Page:       page,
		Scene:      scene,
		EnvVersion: viper.GetString("wechat.miniprogram.envVersion"),
	}
	return s.miniProgram.GetQRCode().GetWXACodeUnlimit(param)
}
